// agent.js
const schedule = require("node-schedule");

module.exports = (agent) => {
  const jobs = {};

  // 创建或修改任务
  agent.messenger.on(
    "scheduleOperation",
    ({ operation, name, time, taskKey }) => {
      switch (operation) {
        case "create":
          if (jobs[name]) {
            jobs[name].cancel(); // 如果已存在，先取消原任务
          }
          const job = schedule.scheduleJob(`${name}`, time, () => {
            // 发送给随机一个 Worker 执行实际的任务逻辑
            agent.messenger.sendRandom("executeServiceMethod", { taskKey });
          });
          jobs[name] = job;
          agent.logger.info(
            `任务 ${name} 已${operation === "create" ? "创建" : "更新"}。`
          );
          break;
        case "update":
          schedule.scheduleJob(`${name}`).reschedule(time);
          break;
        case "cancel":
          if (jobs[name]) {
            jobs[name].cancel();
            delete jobs[name];
            agent.logger.info(`任务 ${name} 已取消。`);
          } else {
            agent.logger.warn(`任务 ${name} 不存在。`);
          }
          break;
        case "invoke":
          agent.messenger.sendRandom("executeServiceMethod", { taskKey });
          break;
        case "reschedule":
          schedule.scheduleJob(`${name}`).reschedule(time);
          break;
        case "list":
          const jobNames = Object.keys(jobs);
          agent.messenger.sendRandom("listScheduleTasks", { jobNames });
          break;
        default:
          agent.logger.warn(`未知操作: ${operation}`);
      }
    }
  );
};
